package com.hyt.it.ogt.ykcj.service.config.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.hyt.it.ogt.pj.feign.tps.TpsClient;
import com.hyt.it.ogt.ykcj.domain.vo.PostSignatureResponseVO;
import com.hyt.it.ogt.ykcj.service.config.IConfigService;
import com.hyt.model.tps.vo.Bucket;
import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.model.PostSignatureRequest;
import com.obs.services.model.PostSignatureResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: it-ogt-tk
 * @description: 配置信息
 * @author: Yang HuanKun
 * @create: 2022-08-18 10:53
 **/
@Slf4j
@Service
public class ConfigServiceImpl implements IConfigService {

    @Resource
    TpsClient tpsClient;

    @Override
    public PostSignatureResponseVO getFileUploadConfig() {
        Bucket bucket = getBucketConfig();
        PostSignatureRequest request = new PostSignatureRequest();
        // 设置表单参数
        Map<String, Object> formParams = new HashMap<>();
        // 设置对象访问权限为公共读
        formParams.put("x-obs-acl", "public-read");

        request.setFormParams(formParams);
        // 设置表单上传请求有效期，单位：秒
        request.setExpires(3600);
        PostSignatureResponse postSignature = getObsClient().createPostSignature(request);
        PostSignatureResponseVO postSignatureResponseVO = BeanUtil.toBean(postSignature, PostSignatureResponseVO.class);
        postSignatureResponseVO.setAccessKey(bucket.getAccessKey());
        postSignatureResponseVO.setDomain(bucket.getDomain());
        postSignatureResponseVO.setBucket(bucket.getBucket());
        postSignatureResponseVO.setEndPoint(bucket.getEndPoint());
        return postSignatureResponseVO;
    }

    /**
     * 使用永久凭证，单例模式
     *
     * @return
     */
    private ObsClient getObsClient() {
        Bucket bucket = getBucketConfig();
        ObsConfiguration config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(bucket.getEndPoint());
        return new ObsClient(bucket.getAccessKey(), bucket.getSecretKey(), config);
    }


    public Bucket getBucketConfig() {
        Bucket bucket = null;
        try {
            String json = tpsClient.getBucketTempCredential();
            if (StringUtils.isNotEmpty(json)) {
                bucket = JSON.parseObject(json, Bucket.class);
            }
        } catch (Exception e) {
            log.error("未获取到华为云文件上传配置:{}", e);

        }
        return bucket;
    }
}
